# THIS SOFTWARE IS A PART OF FASTLBRY PROJECT
# THIS IS A SERVER SOFTWARE FOR FASTLBRY HTML
# THE FOLLOWING SOURCE CODE I UNDER THE GNU
# AGPL LICENSE V3 OR ANY LATER VERSION.

# This project is not for simple users, but for
# web-masters and a like, so we are counting on
# your ability to install an LBRY SDK by your
# self.

SDK = "/home/vcs/Software/FastLBRY-GTK/flbry/lbrynet"
CSS = "https://zortazert.codeberg.page/style/styles.css"
PORT = 8026

# Server side
from http.server import BaseHTTPRequestHandler, HTTPServer
from subprocess import *
import json
import os

from flbry import markdown

# Who fucking made this http.server so I need to use classes?
# I fucking hate who ever thought that it was a good idea...

class handler(BaseHTTPRequestHandler):

    def start_page(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def send(self, text):
        text = str(text)
        csstext = '<link media="all" href="'+CSS+'" type="text/css" rel="stylesheet" />'
        text = '<head>'+csstext+'</head><body>'+text+'</body>'
        

        
        self.start_page()
        self.wfile.write(text.encode("utf-8"))
        
    def do_GET(self):
        print(self.path)
        url = self.path[1:]
        out = check_output([SDK,
                            "resolve", url])

        # Now we want to parse the json

        try:
            out = json.loads(out)
        except:
            self.send("Connect to LBRY first.")
            return
        out = out[url]

        # If article in md

        if out.get("value", {}).get("source", {}).get("media_type") == "text/markdown":
            print("MARKDOWN DETECTED")
            # Then we want to tell the SDK to start downloading.
            playout = check_output([SDK,
                                    "get", url])
            # Parsing the Json
            playout = json.loads(playout)

            # Present the article to the user.
            self.send(markdown.convert(playout['download_path']))
        
serve = HTTPServer(("", PORT), handler)
serve.serve_forever()
